package com.smile.cloud.nettyService.handler;


import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 实现心跳的hander  支持超时断开客户端避免浪费资源
 *
 * @author yangzj
 * @date 2021-09-03 09:41:36
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class ServerHeartHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("建立客户端连接 :{}", ctx.channel().toString());
        super.channelActive(ctx);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("客户端说 :{}", msg.text());
        ctx.writeAndFlush(new TextWebSocketFrame("服务端说：已经收到！"))
                .addListener(ChannelFutureListener.CLOSE);
        if (ctx.channel().isOpen()) {
            //触发下一个handler
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("Channel :{}, , message : {}", ctx.channel().id(), "====客户端断开链接,错误详情： " + cause);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("Channel :{}, , message : {}", ctx.channel().id(), "====断开客户端连接====");
    }

}
